#!/usr/bin/env bash
# Automatic installation script for pre-commit hooks
# Run this script after git clone to set up pre-commit hooks

set -e

echo "Setting up pre-commit hooks..."

# Check if we're in a git repository
if [ ! -d ".git" ]; then
    echo "Error: Current directory is not a git repository"
    exit 1
fi

# Check if pre-commit config file exists
if [ ! -f ".pre-commit-config.yaml" ]; then
    echo "Error: .pre-commit-config.yaml file not found"
    exit 1
fi

# Check if pre-commit is installed
if ! command -v pre-commit &> /dev/null; then
    echo "Warning: pre-commit not detected, attempting to install..."
    
    # Try to install using system package manager first
    if command -v apt-get &> /dev/null; then
        echo "Attempting to install via apt-get..."
        if sudo apt-get update && sudo apt-get install -y pre-commit; then
            echo "Successfully installed pre-commit via apt-get"
        else
            echo "Failed to install via apt-get. Please install manually using pip:"
            echo "  pip install pre-commit"
            echo "  # or"
            echo "  pip3 install pre-commit"
            exit 1
        fi
    elif command -v yum &> /dev/null; then
        echo "Attempting to install via yum..."
        if sudo yum makecache && sudo yum install -y pre-commit; then
            echo "Successfully installed pre-commit via yum"
        else
            echo "Failed to install via yum. Please install manually using pip:"
            echo "  pip install pre-commit"
            echo "  # or"
            echo "  pip3 install pre-commit"
            exit 1
        fi
    else
        echo "No supported package manager found (apt-get/yum)."
        echo "Please install pre-commit manually using pip:"
        echo "  pip install pre-commit"
        echo "  # or"
        echo "  pip3 install pre-commit"
        exit 1
    fi
fi

# Install pre-commit hooks
echo "Installing pre-commit hooks..."
pre-commit install

# Optional: Run pre-commit once to ensure environment is set up correctly
echo "Validating pre-commit configuration..."
pre-commit run --all-files || true

echo "✅ Pre-commit hooks installation completed!"
echo ""
echo "The following checks will now run automatically on each commit:"
echo "  - File size limit (max 9.9MB)"
echo "  - File count limit (max 100 files)"
echo ""
echo "To modify limits, edit the .pre-commit-config.yaml file"
